<template>
  <div class="music-list-wrap">
    <div>
      <div @click="playAllMusic" class="play-all" v-if="playallShow">
        <div class="play-all-icon">
          <span class="icon-play"></span>
        </div>
        <div class="play-all-msg">播放全部</div>
      </div>
      <div v-for="(item, index) in songs" class="each-music" :key="item.id">
        <div class="each-music-index" v-if="indShow">{{ index + 1 }}</div>
        <div class="each-music-msg" @click="playMusic(item.id, index)">
          <div class="each-music-name">{{ item.name }}</div>
          <div class="each-music-artists">
            <div v-if="item.artists">
              <span v-for="(artists, index) in item.artists" :key="artists.id"
                >{{ artists.name
                }}<span v-if="index < item.artists.length - 1">/</span></span
              >
              - <span>{{ item.album.name }}</span>
            </div>
            <div v-else>
              <span v-for="(artists, index) in item.ar" :key="artists.id"
                >{{ artists.name
                }}<span v-if="index < item.ar.length - 1">/</span></span
              >
              - <span>{{ item.al.name }}</span>
            </div>
          </div>
        </div>
        <div class="each-music-more" @click="openBottomSheet(item)">
          <span class="icon-省略"></span>
        </div>
      </div>
    </div>
    <mu-bottom-sheet :open="bottomSheet" @close="closeBottomSheet">
      <mu-list @itemClick="closeBottomSheet">
        <mu-sub-header> 歌曲: {{ msg && msg.name }} </mu-sub-header>
        <mu-list-item title="下一首播放" @click="next(msg)"> </mu-list-item>
        <mu-list-item title="收藏到歌单" @click="collection(msg && msg.id)" />
        <mu-list-item title="评论" @click="toComment(msg && msg.id)" />
        <mu-list-item
          :title="'歌手:' + artistNames"
          @click="toArtist(artist[0].id)"
        >
        </mu-list-item>
        <mu-list-item :title="'专辑:' + albumName" @click="toAlbum(albums.id)">
        </mu-list-item>
        <mu-list-item title="查看MV" @click="toMV(mvId)" v-if="mvId">
        </mu-list-item>
      </mu-list>
    </mu-bottom-sheet>
    <more-msg
      :msg="moreMsg"
      class="more-msg"
      v-if="isShow"
      @hidden="hideMore"
    ></more-msg>
  </div>
</template>

<script lang="ts">
import moreMsg from "./moreMsg.vue";
import { Vue, Component, Prop, Emit, Watch } from "vue-property-decorator";
import { namespace } from "vuex-class";
import Router from "vue-router";
import { Artist, MusicInfo } from "@/model/music-info.model";
import { APIType } from "@/api";
import { CommentType, CommonIdType } from "@/model/id-or-enum.model";
import { CurrentMusic } from "@/model/current-music.model";
const AppModule = namespace("app");
@Component({
  components: {
    moreMsg,
  },
})
export default class MusicListComponent extends Vue {
  isShow = false;
  bottomSheet = false;
  artistNames = "";
  albumName = "";
  @Prop({ required: true, default: [] })
  songs: MusicInfo[];
  @Prop({
    default: true,
  })
  indShow: boolean;
  @Prop({ default: true })
  playallShow: boolean;

  @Watch("songs", {immediate: true})
  private songsChange(value: MusicInfo[]) {
    value?.forEach(x => {
      x.artists = x.ar = x.ar || x.artists;
      x.album = x.al = x.al || x.album;
    });
  }

  @AppModule.State("moreMsg")
  moreMsg: MusicInfo;
  @AppModule.State("musicUrlList")
  musicUrlList: MusicInfo[];
  @AppModule.State("nowMusic")
  nowMusic: CurrentMusic;

  @AppModule.Mutation("addToMusicList")
  addToMusicList: (music: MusicInfo, index?: number) => void;
  @AppModule.Mutation("setCurrentMusicInfo")
  setCurrentMusicInfo: (info: CurrentMusic) => void;
  @AppModule.Mutation("setIsPlaying")
  setIsPlaying: (value: boolean) => void;
  @AppModule.Mutation("setShowController")
  setShowController: (value: boolean) => void;
  @AppModule.Mutation("setMoreMsg")
  setMoreMsg: (info: MusicInfo) => void;
  @AppModule.Mutation("setCommentType")
  setCommentType: (type: CommentType) => void;

  $api: APIType;
  $router: Router;

  get msg() {
    return this.moreMsg;
  }
  get artist() {
    return this.moreMsg?.artists || this.moreMsg?.ar;
  }
  get albums() {
    return this.moreMsg?.album || this.moreMsg?.al;
  }
  get mvId() {
    return this.moreMsg?.mvid || this.moreMsg?.mv;
  }

  playAllMusic() {
    if (!this.songs?.length) return;
    this.playMusic(this.songs?.[0]?.id, 0, true, this.musicUrlList.length);
    for (let song of this.songs) {
      let { id, mp3Url, name, album, al, artists, ar } = song;
      let imgUrl;
      // 由于专辑列表与排行榜的数据结构存在一点差距，所以需要判断数据结构，然后解构赋值
      if (album) {
        ({ blurPicUrl: imgUrl } = album);
      } else {
        ({ picUrl: imgUrl } = al);
      }
      let musicObj: MusicInfo = {
        ...song,
        id,
        url: mp3Url,
        name,
        artists: artists || ar,
        imgUrl,
      };
      this.addToMusicList(musicObj);
    }
  }
  // id是音乐id，ind是即将播放的音乐在页面音乐列表的序列号，ifadd表示是否要添加这个即将播放的音乐到列表，len表示音乐仓库的长度
  playMusic(id: CommonIdType, index: number, ifAdd?: boolean, len?: number) {
    // console.log(index)
    this.$api.getMusicUrl(id).then((res) => {
      // console.log(ind)
      // 这个ind是页面音乐列表的序列
      let artists: Artist[];
      let imgUrl: string;
      if (this.songs[index].album) {
        artists = this.songs[index].artists;
        imgUrl = this.songs[index].album.blurPicUrl;
      } else {
        imgUrl = this.songs[index].al.picUrl;
        artists = this.songs[index].ar;
      }
      // console.log(this.musicUrlList.length)
      let nowIndex = null;
      if (len || len === 0) {
        nowIndex = len;
      } else {
        nowIndex = this.musicUrlList.length;
      }
      // console.log(len)
      // console.log(nowInd)
      // 下面这个ind是当前播放音乐在音乐仓库的序列
      const info: CurrentMusic = {
        id: this.songs[index].id,
        index: nowIndex,
        nowMusicUrl: res[0].url,
        nowName: this.songs[index].name,
        nowArtists: artists,
        nowImgUrl: imgUrl,
      };
      const music: MusicInfo = {
        ...this.songs[index],
        imgUrl,
        id,
        url: res[0].url,
        name: this.songs[index].name,
        artists,
      };
      this.setCurrentMusicInfo(info);
      this.setIsPlaying(true);
      this.setShowController(true);
      if (ifAdd) {
        return;
      }
      this.addToMusicList(music);
    });
  }
  hideMore() {
    this.isShow = false;
  }
  closeBottomSheet() {
    this.bottomSheet = false;
  }
  openBottomSheet(music: MusicInfo) {
    this.setMoreMsg(music);
    const ar = this.msg.ar ? this.msg.ar : this.msg.artists;
    this.artistNames = ar.map((x) => x.name).join(",");
    this.albumName = this.msg?.al?.name ?? this.msg?.album?.name;
    this.bottomSheet = true;
  }
  next(music: MusicInfo) {
    let {
      artists,
      id,
      name,
      album: { picUrl },
      mp3Url,
    } = music;
    const info: MusicInfo = {
      ...music,
      artists,
      id,
      imgUrl: picUrl,
      name,
      url: mp3Url,
    };
    this.addToMusicList(info);
    this.hiddenAction();
  }
  @Emit("hidden")
  hiddenAction() {}
  collection(id: CommonIdType) {
    // TODO: 动态获取歌单id
    const playListId = 495727117;
    this.$api.operatePlayList("add", playListId, id).then(() => {
      this.hiddenAction();
    });
  }
  toComment(id: CommonIdType) {
    this.setCommentType(CommentType.ToSong);
    this.$router.push({ path: `/comment/${id}` }).catch((err) => err);
  }
  toArtist(id: CommonIdType) {
    // console.log(id: CommonIdType)
    this.$router.push({ path: `/artist/${id}` }).catch((err) => err);
  }
  toAlbum(id: CommonIdType) {
    this.$router.push({ path: `/album/${id}` }).catch((err) => err);
  }
  toMV(id: CommonIdType) {
    this.$router.push({ path: `/mv/${id}` }).catch((err) => err);
  }
}
</script>

<style lang="scss" scoped>
.left-icon {
  line-height: 0.8rem;
  text-align: center;
  width: 0.8rem;
  height: 0.8rem;
  color: #999;
  font-size: 0.2rem;
}
$border: 1px solid #e1e6e4;
.play-all {
  display: flex;
  border-bottom: $border;
  background-color: #f1f6f4;
  .play-all-icon {
    @extend .left-icon;
  }
  .play-all-msg {
    flex: 1;
    font-size: 0.18rem;
    line-height: 0.8rem;
  }
}
.each-music {
  display: flex;
  height: 0.8rem;
  background-color: #f1f6f4;
  .each-music-index {
    @extend .left-icon;
  }
  .each-music-msg {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    border-bottom: $border;
    .each-music-name {
      color: #343937;
      font-size: 0.16rem;
      font-weight: 500;
    }
    .each-music-artists {
      color: #a1a6a4;
      font-size: 0.12rem;
    }
  }
  .each-music-more {
    color: #babfbd;
    line-height: 0.8rem;
    border-bottom: $border;
    width: 0.3rem;
    font-size: 0.25rem;
  }
}
</style>
